import React, { Suspense, useEffect } from 'react';
import { BrowserRouter as Router, useRoutes, useNavigate, useLocation } from 'react-router-dom';
import routes from './router/index';
import { isLoggedIn, isRiderActive } from './utils/auth';

// 应用启动时的路由检查组件
const AppInitializer = ({ children }) => {
  const navigate = useNavigate();
  const location = useLocation();

  useEffect(() => {
    // 只在应用启动时检查一次
    const checkInitialAuth = () => {
      // 如果当前在登录页面，不需要检查
      if (location.pathname === '/login') {
        return;
      }

      // 如果当前在待审核页面，检查登录状态
      if (location.pathname === '/pending') {
        if (!isLoggedIn()) {
          navigate('/login');
          return;
        }
        return;
      }

      // 检查是否已登录
      if (!isLoggedIn()) {
        navigate('/login');
        return;
      }

      // 检查骑手状态
      if (!isRiderActive()) {
        navigate('/pending');
        return;
      }

      // 如果已登录且状态正常，但不在主布局页面，跳转到首页
      if (!location.pathname.startsWith('/layout/')) {
        navigate('/layout/home');
      }
    };

    checkInitialAuth();
  }, [navigate, location.pathname]);

  return children;
};

const AppContent = () => {
  const element = useRoutes(routes);
  
  return (
    <div style={{ height: '100vh' }}>
      <AppInitializer>
        <Suspense fallback={<div>Loading...</div>}>
          {element}
        </Suspense>
      </AppInitializer>
    </div>
  );
};

const App = () => {
  return (
    <Router>
      <AppContent />
    </Router>
  );
};

export default App;




